<template>
  <t-dialog
    title="新建全局铺码"
    height="700px"
    v-loading="loading"
    :element-loading-text="loadingText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :visible="visible"
    :bodyScrollY="true"
    @onClickFooterButton="onClickFooterButton"
  >
    <el-form label-position="top" :model="form" ref="form" :rules="rules">
      <el-form-item label="选择手写码Key：" prop="writecode">
        <el-upload
          ref="uploadKey"
          accept=".tmx"
          action=""
          :show-file-list="false"
          :before-upload="checkWriteKeyFileType"
          :http-request="getWriteKey"
          :limit="1"
          ><el-button slot="trigger" size="small" type="primary">
            上传KEY文件
          </el-button>
        </el-upload>
        <el-descriptions
          class="mt-2"
          :labelStyle="{ 'text-align': 'center' }"
          :contentStyle="{ 'text-align': 'center' }"
          :column="5"
          border
          direction="vertical"
          size="mini"
        >
          <el-descriptions-item label="SID">
            {{ form.writecode.sid }}
          </el-descriptions-item>
          <el-descriptions-item label="OID">
            {{ form.writecode.oid }}
          </el-descriptions-item>
          <el-descriptions-item label="BID">
            {{ form.writecode.bid }}
          </el-descriptions-item>
          <el-descriptions-item label="PageID">
            {{ form.writecode.minPid }}-{{ form.writecode.maxPid }}
          </el-descriptions-item>
          <el-descriptions-item label="有效期">
            {{ form.writecode.expiryDate }}
          </el-descriptions-item>
        </el-descriptions>
      </el-form-item>
      <el-form-item label="上传PDF文件：" prop="urlpath">
        <el-upload
          ref="uploadPdf"
          accept=".pdf"
          action=""
          :before-upload="beforeUploadPDFFile"
          :http-request="uploadPDFFile"
          :disabled="uploadPDFFileDisabled"
          :limit="1"
        >
          <el-button
            slot="trigger"
            size="small"
            type="primary"
            @click="onClickUploadPdfButton"
          >
            上传PDF文件
          </el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="页面范围：" prop="pageRange">
        <el-radio-group v-model="form.pageRange" @change="radioChange">
          <el-radio
            v-for="i in $options.constants.pageRangeList"
            :key="i.label"
            :label="i.value"
            >{{ i.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="铺码方式：" prop="codepointmode">
        <el-select
          class="w-full"
          v-model="form.codepointmode"
          placeholder="请选择铺码方式"
          @change="() => (this.form.codepointsize = 0)"
          ><el-option
            v-for="i in $options.constants.codepointmodeList"
            :key="i.value"
            :label="i.label"
            :value="i.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="码点间距：" prop="codepointsize">
        <el-radio-group v-model="form.codepointsize">
          <el-radio
            v-for="i in $options.constants.codepointsizeList"
            :key="i.value"
            :label="i.value"
            :disabled="isDisabledRadio(i.value)"
            >{{ i.label }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.pageRange === 0"
        label="起始页pageId："
        prop="startpageid"
      >
        <el-input v-model.number="form.startpageid"></el-input>
      </el-form-item>
      <el-form-item v-else label="指定页：" prop="pagesinfo">
        <div class="space-y-2">
          <div class="flex" v-for="i in form.pagesinfo" :key="i.key">
            <span>需要铺码的文档页码：</span>
            <el-input
              class="w-28"
              placeholder="请输入文档页码"
              v-model.number="i.pagenumber"
            ></el-input>
            <div class="flex-1"></div>
            <span>对应铺码pageId：</span>
            <el-input
              class="w-28"
              placeholder="请输入pageId"
              v-model.number="i.pageid"
            ></el-input>
          </div>
          <div
            class="text-center border-2 border-dashed"
            @click="onClickAddSpecifyPageButton"
          >
            <i class="el-icon-plus"></i>
            <span>添加</span>
          </div>
        </div>
      </el-form-item>
      <!-- 自定义 -->
      <div v-if="form.codepointmode === 0">
        <el-form-item label="PDF文档铺码类型：" prop="codepointtype">
          <el-select
            class="w-full"
            v-model="form.codepointtype"
            placeholder="请选择铺码类型"
          >
            <el-option
              v-for="i in $options.constants.codepointtypeList"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="铺码码点大小：" prop="imagesize">
          <el-select
            class="w-full"
            v-model="form.imagesize"
            placeholder="请选择码点大小"
          >
            <el-option
              v-for="i in $options.constants.imagesizeList"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="铺码文件打印机DPI：" prop="imagedpi">
          <el-select
            class="w-full"
            v-model="form.imagedpi"
            placeholder="请选择打印机DPI"
            @change="() => (this.form.codepointsize = 0)"
          >
            <el-option
              v-for="i in $options.constants.imagedpiList"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="铺码模式：" prop="pdftype">
          <el-select
            class="w-full"
            v-model="form.pdftype"
            placeholder="请选择铺码模式"
          >
            <el-option
              v-for="i in $options.constants.pdftypeList"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
      </div>
    </el-form>
  </t-dialog>
</template>

<script>
import * as global from "@/apis/global-spread-code";
import { getSpreadCodeSchedule } from "@/apis/spread-code-schedule";
import TDialog from "@/components/TDialog.vue";
// import oss from "@/common/ali-oss";
import {
  codepointmode,
  codepointtype,
  imagesize,
  imagedpi,
  pdftype,
  codepointsize,
} from "@/common/constants";
import {
  checkPDFFileType,
  checkWriteKeyFileType,
  checkWriteCodeKey,
  getWriteKey,
  getPDFData,
  loading,
} from "@/common/utils";
export default {
  components: { TDialog },
  constants: {
    pageRangeList: [
      { label: "全部", value: 0 },
      { label: "指定页", value: 1 },
    ],
    codepointmodeList: codepointmode,
    codepointtypeList: codepointtype,
    imagesizeList: imagesize,
    imagedpiList: imagedpi,
    pdftypeList: pdftype,
    codepointsizeList: codepointsize,
  },
  data() {
    // pagesinfo 非空判断
    const pagesinfoCustomValidate = (rule, value, callback) => {
      //非空判断
      const isEmpty = value.every((i) =>
        [i.pageid, i.pagenumber].every((j) => j !== "")
      );
      if (!isEmpty) {
        return callback(new Error("请将指定页信息填写完整！"));
      }
      callback();
    };
    return {
      loading: false,
      loadingText: "",
      visible: false,
      form: {
        //pdf路径
        pdfPageNumbers: "",
        urlpath: "",
        //
        writecode: {
          sid: 0,
          oid: 0,
          bid: 0,
          pid: 0,
          minPid: 0,
          maxPid: 0,
          expiryDate: "0/0/0",
          value: "",
        },
        // 起始页id
        startpageid: 0,
        //
        pagesinfo: [{ pagenumber: 0, pageid: 0, key: 0 }],
        // 铺码范围
        pageRange: 0,
        // 码点间距
        codepointsize: 0,
        //铺码方式
        codepointmode: 1,
        //PDF文档码点类型
        codepointtype: 0,
        //铺码码点大小
        imagesize: 1,
        //打印机DPI
        imagedpi: 0,
        //铺码模式
        pdftype: 0,
      },
      rules: {
        writecode: [
          { required: true, message: "请选择铺码KEY文件", trigger: "blur" },
          { validator: checkWriteCodeKey, trigger: "blur" },
        ],
        urlpath: [
          { required: true, message: "请上传PDF文件", trigger: "blur" },
        ],
        pageRange: [
          { required: true, message: "请选择页面范围", trigger: "blur" },
        ],
        startpageid: [
          { required: true, message: "请输入起始pageId", trigger: "blur" },
        ],
        pagesinfo: [
          { required: true, message: "请输入指定页信息", trigger: "blur" },
          { validator: pagesinfoCustomValidate, trigger: "blur" },
        ],
        codepointmode: [
          { required: true, message: "请选择铺码方式", trigger: "blur" },
        ],
        codepointtype: [
          { required: true, message: "请选择铺码类型", trigger: "blur" },
        ],
        imagesize: [
          { required: true, message: "请选择码点大小", trigger: "blur" },
        ],
        imagedpi: [
          { required: true, message: "请选择打印机DPI", trigger: "blur" },
        ],
        pdftype: [
          { required: true, message: "请选择铺码模式", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // pdf上传禁用
    uploadPDFFileDisabled({ form }) {
      if (!form.writecode.value) {
        return true;
      }
      //过期判断
      if (Date.now() > new Date(form.writecode.expiryDate).getTime()) {
        return true;
      }
      return false;
    },
    isDisabledRadio({ form: { codepointmode, imagedpi } }) {
      return (value) => {
        if (value !== 1) {
          return false;
        }
        if (codepointmode === 0) {
          return imagedpi === 0;
        } else {
          return [1, 2].includes(codepointmode);
        }
      };
    },
  },
  methods: {
    open() {
      this.visible = true;
    },
    //下载已铺好的PDF
    async getFileUrl(fileUrl) {
      const res = await global.getFileUrl(fileUrl);
      console.log("获取已铺码的PDF", res);
      //返回状态
      if (res.data.state.code === 10000) {
        //成功
        res.data.result.filesname.map((i) => window.open(i, "_blank"));
      } else {
        //失败
        this.$message.error("获取铺码文件失败");
      }
    },
    // 获取KEY文件之前 - 校验文件类型
    checkWriteKeyFileType(file) {
      return checkWriteKeyFileType(file);
    },
    // 获取文件中的key
    async getWriteKey(file) {
      this.form.writecode = await getWriteKey(file);
      this.$refs.form.validateField("writecode");
      this.$refs.uploadKey.clearFiles();
    },
    // 点击上传按钮
    onClickUploadPdfButton() {
      this.$refs.form.validateField("writecode");
    },
    // 上传PDF文件之前 - 校验文件
    async beforeUploadPDFFile(file) {
      // 验证文件扩展名
      if (!checkPDFFileType(file)) {
        this.$message.warning("请上传pdf类型的文件");
        return Promise.reject();
      }
      // 获取页码数
      const { numPages } = await loading({
        text: "读取PDF文件中...",
        fn: async () => await getPDFData(file),
      });
      if (numPages > this.form.writecode.maxPid) {
        this.$message.warning("PDF文件页码超出Key中PageId范围");
        return Promise.reject();
      }
      return Promise.resolve();
    },
    // 上传PDF文件
    async uploadPDFFile(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const blob = new Blob([e.target.result], { type: file.file.type });
        const url = URL.createObjectURL(blob);
        this.form.pdfName = file.file.name; // 新增：记录PDF文件名
        this.form.urlpath = url; // 更新：使用本地URL
        this.$message.success(`${this.form.pdfName}上传成功`);
        this.$refs.form.validateField("urlpath");
      };
      reader.readAsArrayBuffer(file.file);
      this.$refs.uploadPdf.clearFiles(); // 清除上传组件的文件列表
    },
    //单选元素绑定之变化触发
    radioChange() {
      //清除表单验证消息
      this.$refs.form.clearValidate();
    },
    //点击添加指定页
    onClickAddSpecifyPageButton() {
      const list = this.form.pagesinfo;
      const lastElement = list[list.length - 1];
      list.push({
        pagenumber: lastElement.pagenumber + 1,
        pageid: lastElement.pageid + 1,
        key: lastElement.key + 1,
      });
    },
    //点击铺码弹窗底部按钮
    onClickFooterButton(name) {
      switch (name) {
        case "取消": {
          this.visible = false;
          break;
        }
        case "确定": {
          this.submit();
          break;
        }
      }
    },
    //表单提交
    async submit() {
      const valid = await new Promise((resolve) =>
        this.$refs.form.validate(resolve)
      );
      if (!valid) return;
      const params = {
        urlpath: this.form.urlpath,
        writecode: this.form.writecode.value,
        // 页码范围
        ...(this.form.pageRange === 0
          ? { startpageid: this.form.startpageid }
          : { pagesinfo: this.form.pagesinfo }),
        codepointmode: this.form.codepointmode,
        codepointsize: this.form.codepointsize,
        codepointinfo:
          this.form.codepointmode === 0
            ? null
            : {
                codepointtype: this.form.codepointtype,
                imagesize: this.form.imagesize,
                imagedpi: this.form.imagedpi,
                pdftype: this.form.pdftype,
              },
      };
      this[
        ["fullPageSpreadCode", "specifiedPageSpreadCode"][this.form.pageRange]
      ](params);
    },
    //整页铺码
    async fullPageSpreadCode({
      urlpath,
      writecode,
      startpageid,
      codepointmode,
      codepointtype,
      imagesize,
      imagedpi,
      pdftype,
    }) {
      // 接口基础参数 非自定义
      let params = { urlpath, writecode, startpageid, codepointmode };
      // 自定义铺码方式
      if (codepointmode === 0) {
        params = { ...params, codepointtype, imagesize, imagedpi, pdftype };
      }
      const res = await global.fullPageSpreadCode(params);
      console.log("整页铺码", res);
      if (res.data.state.code === 10000) {
        // 成功
        // get 轮询 获取铺码进度
        this.getSpreadCodeSchedule(urlpath);
      } else {
        // 失败
      }
    },
    // 指定页铺码
    async specifiedPageSpreadCode({
      urlpath,
      writecode,
      pagesinfo,
      codepointmode,
      codepointtype,
      imagesize,
      imagedpi,
      pdftype,
    }) {
      //过滤掉key字段
      pagesinfo = pagesinfo.map(({ pageid, pagenumber }) => {
        return { pageid, pagenumber };
      });
      // 接口基础参数 非自定义
      let params = { urlpath, writecode, pagesinfo, codepointmode };
      // 自定义铺码方式
      if (codepointmode === 0) {
        params = { ...params, codepointtype, imagesize, imagedpi, pdftype };
      }
      const res = await global.specifiedPageSpreadCode(params);
      console.log("指定页铺码", res);
      if (res.data.state.code === 10000) {
        //成功
        // get 轮询 获取铺码进度
        this.getSpreadCodeSchedule(urlpath);
      } else {
        //失败
      }
    },
    // 获取铺码进度
    getSpreadCodeSchedule(filepath) {
      this.loading = true;
      this.loadingText = "全局铺码中...";
      let timer = setInterval(async () => {
        const res = await getSpreadCodeSchedule(filepath);
        console.log("获取铺码进度", res);
        const {
          result: { speed, finish, message, filesname },
        } = res.data;
        this.loadingText = `${parseFloat((speed * 100).toFixed(2))}%`;
        if (speed === 1) {
          clearInterval(timer);
          this.loading = false;
          if (finish === 10000) {
            this.$confirm("铺码成功，是否下载已铺好的PDF", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "success",
            })
              .then(() => {
                filesname.map((i) => window.open(i, "_blank"));
              })
              .catch(() => false);
          } else {
            this.$alert(message, "请求异常", {
              showClose: false,
              confirmButtonText: "确定",
            });
          }
        }
      }, 1000);
    },
  },
};
</script>